package com.example.xmh.emo.mysql.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.xmh.business.reserve.BReserve;
import com.example.xmh.emo.mysql.system.entity.Reserve;
import com.example.xmh.emo.mysql.system.mapper.ReserveMapper;
import com.example.xmh.entity.Resp;
import com.example.xmh.utils.CheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xmh
 * @since 2021-11-12
 */
@RestController
@RequestMapping("/reserve")
public class ReserveController {
    @Autowired
    ReserveMapper reserveMapper;

    @GetMapping("/get")
    public Resp<Object> GetReserve(@RequestParam String phoneNumber, @RequestParam String area, @RequestParam String channel) {

        if (!BReserve.hasArea(area)) {
            return new Resp<>(200, "区域错误", null);
        }
        if (!BReserve.hasChannel(channel)) {
            return new Resp<>(200, "渠道错误", null);
        }
        if (!CheckUtils.isMobileWeak(phoneNumber)) {
            return new Resp<>(200, "手机号错误", null);
        }

        Reserve reserve = reserveMapper.selectOne(new QueryWrapper<Reserve>().eq("phone_number", phoneNumber));

        if (reserve == null) {
            String code = BReserve.createReserveCode();
            reserveMapper.insert(new Reserve(0, phoneNumber, area, channel, code, false));
            return new Resp<>(200, "预约成功", code);
        } else {
            return new Resp<>(200, "该手机号已预约", reserve);
        }
    }

    @GetMapping("/getAward")
    public Resp<Object> GetAward(@RequestParam String phoneNumber, @RequestParam String code) {
        if (!CheckUtils.isMobileWeak(phoneNumber)) {
            return new Resp<>(200, "手机号错误", false);
        }

        Reserve reserve = reserveMapper.selectOne(new QueryWrapper<Reserve>().eq("phone_number", phoneNumber));

        if (reserve.getReserveCode().equals(code)) {
            if (!reserve.isUsed()) {
                reserveMapper.update(null, new UpdateWrapper<Reserve>().eq("phone_number", phoneNumber).set("is_used", true));
                return new Resp<>(200, "领取成功！", true);
            } else {
                return new Resp<>(200, "请勿重复领取", false);
            }
        } else {
            return new Resp<>(200, "预约码错误", false);
        }
    }
}
